<script setup>
import {reactive, ref} from 'vue';

import {FeeGenerateRec} from "@/script/model/tables/FeeGenerateRec";
import {IncGenerateRec} from "@/script/model/tables/IncGenerateRec";
import {OutcGenerateRec} from "@/script/model/tables/OutcGenerateRec";
import {IncOutcBalanceRec} from "@/script/model/tables/IncOutcBalanceRec";

import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";
import AccountRecTab from "@/views/app/AccountBalance/AccountRecTable.vue";
import AccountBalHelpPopover from "@/views/app/AccountBalance/AccountBalHelpPopover.vue";

/**
 * 数据读取相关变量
 */
const selectedDate = ref(''); // 用户所选日期
const tableGroup = reactive({feeGenes: [], incGenes: [], outcGenes: []}) // 报表数据;
const balanceReport = reactive({dayBal: [], historyBal: []});

const feeGenesTableColInfo = ref([]); // 费用发生表表头信息
const incGenesTableColInfo = ref([]); // 收入表表头信息
const outcGenesTableColInfo = ref([]); // 支出表表头信息
const incOutcBalanceColInfo = ref([]); // 收支平衡表表头信息
feeGenesTableColInfo.value = FeeGenerateRec.tableColumn;
incGenesTableColInfo.value = IncGenerateRec.tableColumn;
outcGenesTableColInfo.value = OutcGenerateRec.tableColumn;
incOutcBalanceColInfo.value = IncOutcBalanceRec.tableColumn;

/**
 * 表格相关操作变量
 */
const selBalRecRows = ref([]); // 选中行
const selHisBalRows = ref([]);

// 选中收支平衡记录行
const selectBalRecRow = (selection) => {
  // 每次选定行，先弹出当前旧选中列表，再添加新选中列表
  selBalRecRows.value.pop();
  selBalRecRows.value.push(selection);
}

// 选中历史收支平衡记录行
const selectHisBalRow = (selection) => {
  selHisBalRows.value.pop();
  selHisBalRows.value.push(selection);
}

// 删除当日收支平衡记录行
const deleteAllSelectedDayBalRow = () => {
  if (selBalRecRows.value.length === 0) {
    // 如果未选中任何元素，则报出错误提示
    ElMessage({message: "无法操作，请勾选记录后再删除！", type: 'error'});
  } else {
    // 如果选中元素，则执行删除操作，避免误操作先执行判断
    ElMessageBox.confirm(
        '确认要删除选中的记录吗？操作无法撤销',
        '警告', {confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning'}
    ).then(() => {
      // 确认执行删除操作
      ElMessage({message: "删除" + selBalRecRows.value[0].length + "条记录，误操作请重新导入", type: "success"});
      balanceReport.dayBal = balanceReport.dayBal.filter(balRec => selBalRecRows.value[0].indexOf(balRec) === -1);
      // 最后将选中表清空
      selBalRecRows.value.pop();
    }).catch(() => ElMessage({message: "已取消操作", type: "warning"}));
  }
}

// 删除历史收支平衡记录行
const deleteAllSelectedHisBalRow = () => {
  if (selHisBalRows.value.length === 0) {
    // 如果未选中任何元素，则报出错误提示
    ElMessage({message: "无法操作，请勾选记录后再删除！", type: 'error'});
  } else {
    // 如果选中元素，则执行删除操作，避免误操作先执行判断
    ElMessageBox.confirm(
        '确认要删除选中的记录吗？操作无法撤销',
        '警告', {confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning'}
    ).then(() => {
      // 确认执行删除操作
      ElMessage({message: "删除" + selHisBalRows.value[0].length + "条记录", type: "success"});
      balanceReport.historyBal = balanceReport.historyBal.filter(balRec => selHisBalRows.value[0].indexOf(balRec) === -1);
      // 最后将选中表清空
      selHisBalRows.value.pop();
      // 后端对应修改
      axios.post("http://localhost:30601/fms/accounting/modify-history", balanceReport.historyBal);
    }).catch(() => ElMessage({message: "已取消操作", type: "warning"}));
  }
}

// 清空所有报表数据
const cleanAllTable = () => {
  tableGroup.feeGenes = [];
  tableGroup.incGenes = [];
  tableGroup.outcGenes = [];
  balanceReport.dayBal = [];
}

// 读取指定日期的报表数据
const loadOriginAccountingTable = () => {
  // 首先清空所有数据
  cleanAllTable();
  // 重新捕捉选定数据
  axios.get('http://localhost:30601/fms/accounting/query-all-origin-table',
      {params: {time: selectedDate.value}})
      .then(response => {
        if (response.data.content != null) {
          tableGroup.feeGenes = response.data.content.feeGenes;
          tableGroup.incGenes = response.data.content.incGenes;
          tableGroup.outcGenes = response.data.content.outcGenes;
          balanceReport.historyBal = response.data.content.historyBal;
          console.log(balanceReport);
          ElMessage({message: "操作成功！", type: 'success'});
        } else {
          ElMessage({message: "操作失败，请校验日期参数或检查文件是否存在！", type: 'error'});
        }
      });
};

// 读取收入支出平衡计算结果表
const loadBalanceCalReport = () => {
  axios.get('http://localhost:30601/fms/accounting/inc-outc-balance',
      {params: {time: selectedDate.value}})
      .then(response => {
        if (response.data.content != null) {
          balanceReport.dayBal = response.data.content;
          ElMessage({message: "操作成功！", type: 'success'});
        } else {
          ElMessage({message: "操作失败，请校验日期参数或检查文件是否存在！", type: 'error'});
        }
      });
}

// 存入收入支出平衡计算结果表
const mergeBalanceCalReport = () => {
  axios.post('http://localhost:30601/fms/accounting/merge-inc-outc-to-history',
      balanceReport.dayBal)
      .then(response => {
        if (response.data.content != null) {
          ElMessageBox.confirm(
              '确认要合并记录吗？操作无法撤销',
              '警告', {confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning'}
          ).then(() => {
            ElMessage({message: "已成功合并运算结果！", type: 'success'});
            balanceReport.historyBal = response.data.content;
          }).catch(() => ElMessage({message: "已取消操作", type: "warning"}));
        } else {
          ElMessage({message: "操作失败，请检查当日费用平衡记录表是否为空！", type: "error"});
        }
      });
}
</script>

<template>
  <div class="main-body">
    <div class="passage-title">
      <span>住宿费用平衡统计</span>
      <account-bal-help-popover/>
    </div>
    <div class="account-ctrl-panel">
      <el-button type="primary" size="default" @click="loadOriginAccountingTable">读取报表和历史记录</el-button>
      <el-button type="success" size="default" @click="loadBalanceCalReport">开始计算</el-button>
      <span class="date-selector">
        <el-date-picker v-model="selectedDate" type="date" placeholder="选择报表日期" size="default"
                        format="YYYY-MM-DD" value-format="YYYYMMDD"/>
      </span>
      <el-tabs type="border-card" tab-position="top">
        <account-rec-tab table-label="6-费用发生与押金明细" :table-data="tableGroup.feeGenes"
                         :table-col-info="feeGenesTableColInfo" empty-message="无报表数据"></account-rec-tab>
        <account-rec-tab table-label="4-收入明细" :table-data="tableGroup.incGenes"
                         :table-col-info="incGenesTableColInfo" empty-message="无报表数据"></account-rec-tab>
        <account-rec-tab table-label="3-费用发生明细" :table-data="tableGroup.outcGenes"
                         :table-col-info="outcGenesTableColInfo" empty-message="无报表数据"></account-rec-tab>
        <account-rec-tab table-label="当日费用平衡计算结果" :table-data="balanceReport.dayBal"
                         :table-col-info="incOutcBalanceColInfo" empty-message="收支结果未计算"
                         :select-row-handle="selectBalRecRow">
          <template v-slot:delete>
            <el-button type="danger" size="default" @click="deleteAllSelectedDayBalRow">删除所选行</el-button>
          </template>
          <template v-slot:save>
            <el-button type="success" size="default" @click="mergeBalanceCalReport">合并当日计算结果</el-button>
          </template>
          <template v-slot:select>
            <el-table-column type="selection"/>
          </template>
        </account-rec-tab>
        <account-rec-tab table-label="历史记录" :table-data="balanceReport.historyBal"
                         :table-col-info="incOutcBalanceColInfo" empty-message="无历史记录"
                         :select-row-handle="selectHisBalRow">
          <template v-slot:delete>
            <el-button type="danger" size="default" @click="deleteAllSelectedHisBalRow">删除所选行</el-button>
          </template>
          <template v-slot:select>
            <el-table-column type="selection"/>
          </template>
        </account-rec-tab>
      </el-tabs>
    </div>
  </div>
</template>

<style scoped lang="scss">
@import "../../../style/app/AccountBalanceBody";

.date-selector {
  margin-left: 12px;
}
</style>